<template>
  <div style="width: 1200px;margin: 0 auto;height: 100vh;" class="form">
    <span style="display: flex;justify-content: space-between;padding-top: 10px;" class="but">
      <router-link to="/main/process" style=""><el-button>返回</el-button></router-link>
      <span>
        <span @click="addRecord"><el-button type="success" icon="el-icon-plus">新增</el-button></span>&emsp;
        <span @click="deleteSelectedRecords"><el-button type="danger"
            icon="el-icon-delete">批量删除</el-button></span>&emsp;
        <span @click="saveData"><el-button type="primary" icon="el-icon-check">保存</el-button></span>&emsp;
        <router-link to="/main/renshi/kaoqing/jiabansq-list" style=""><el-button
            icon="el-icon-s-grid">列表</el-button></router-link>
        <el-button v-if="id" type="info" icon="el-icon-share" style="position: absolute;right: 180px;"
          @click="viewProcess">
          流程
        </el-button>&emsp;
        <span @click="printForm"><el-button type="info" icon="el-icon-printer">打印</el-button></span>
      </span>
    </span>

    <h2>深圳市艾美思普科技有限公司</h2>
    <h2 style="padding-top: 0px;">加班申请单</h2>
    <p style="display: flex;align-items: center;padding: 10px 0px;">申请日期：<input style="width: 10%;"
        v-model="applicationDate" type="date" /></p>
    <table border="1">
      <thead>
        <tr>
          <th class="checkbox"><input style="height: 13px;" type="checkbox" @change="toggleSelectAll"
              v-model="selectAll"></th>
          <th>序号</th>
          <th>工号</th>
          <th>姓名</th>
          <th>部门/组别</th>
          <th>加班日期</th>
          <th>加班时间</th>
          <th>共计加班(H)</th>
          <th>加班事由</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(record, index) in overtimeRecords" :key="index">
          <td class="checkbox"><input style="height: 13px;" type="checkbox" v-model="selectedRecords" :value="index"
              @change="updateSelectAll" /></td>
          <td>{{ index + 1 }}</td>
          <td><input v-model="record.employeeId" /></td>
          <td><input v-model="record.name" /></td>
          <td><input v-model="record.department" /></td>
          <td><input v-model="record.overtimeDate" type="date" /></td>
          <td><input v-model="record.overtimePeriod" /></td>
          <td><input v-model="record.totalHours" type="number" /></td>
          <td><input v-model="record.reason" /></td>
        </tr>
        <tr>
          <td colspan="9">
            <div class="approval-info">
              <div class="approval-row">
                <div class="approval-item">
                  <span class="label">申请人：</span>
                  <el-input v-model="applicant" class="input" size="small"></el-input>
                </div>
                <div class="approval-item">
                  <span class="label">审核：</span>
                  <el-input v-model="reviewer" class="input" size="small"></el-input>
                </div>
                <div class="approval-item">
                  <span class="label">批准：</span>
                  <el-input v-model="approver" class="input" size="small"></el-input>
                </div>
              </div>
            </div>
          </td>
        </tr>
      </tbody>
    </table>
    <p style="display: flex;justify-content: space-between;padding: 10px 0px;"> <span>表格编号与版次：AM-FR-007-A0</span>
      <span>保存期限：长期</span>
    </p>

    <!-- 
    <button @click="addRecord">新增</button>
    <button @click="deleteSelectedRecords">批量删除</button> -->


    <!-- <button @click="saveData">保存</button> -->
  </div>
</template>
<script>
import { saveOvertimeApply, getOvertimeApplyDetail } from '@/api/overtimeApply';

export default {
  data() {
    return {
      id: null,
      applicationDate: '',
      overtimeRecords: [this.getEmptyRecord()],
      applicant: '',
      reviewer: '',
      approver: '',
      selectedRecords: [],
      selectAll: false
    };
  },
  created() {
    // 从路由参数中获取id
    const id = this.$route.query.id;
    if (id) {
      this.id = id;
      this.fetchDetail(id);
    }
  },
  methods: {
    viewProcess() {
      if (this.id) {
        this.$router.push({
          path: '/main/renshi/kaoqing/jiabansq-process',
          query: { id: this.id }
        });
      }
    },
    getEmptyRecord() {
      return {
        employeeId: '',
        name: '',
        department: '',
        overtimeDate: '',
        overtimePeriod: '',
        totalHours: 0,
        reason: ''
      };
    },
    async fetchDetail(id) {
      try {
        const response = await getOvertimeApplyDetail(id);
        const detail = response.data;

        // 设置表单数据
        this.overtimeRecords = [{
          id: detail.id,
          employeeId: detail.employeeId,
          name: detail.name,
          department: detail.department,
          overtimeDate: detail.overtimeDate ? detail.overtimeDate.split('T')[0] : '',
          overtimePeriod: detail.overtimePeriod,
          totalHours: detail.totalHours,
          reason: detail.reason
        }];

        // 设置其他字段
        this.applicationDate = detail.applicationDate ? detail.applicationDate.split('T')[0] : '';
        this.applicant = detail.applicant || '';
        this.reviewer = detail.reviewer || '';
        this.approver = detail.approver || '';
      } catch (error) {
        this.$message.error('获取详情失败：' + error.message);
      }
    },
    // 全选功能
    toggleSelectAll() {
      if (this.selectAll) {
        this.selectedRecords = this.overtimeRecords.map((_, index) => index);
      } else {
        this.selectedRecords = [];
      }
    },
    // 更新全选状态
    updateSelectAll() {
      this.selectAll = this.selectedRecords.length === this.overtimeRecords.length;
    },
    // 批量删除功能
    deleteSelectedRecords() {
      if (confirm('确定要删除选中的记录吗？')) {
        this.selectedRecords.sort((a, b) => b - a).forEach(index => {
          this.overtimeRecords.splice(index, 1);
        });
        this.selectedRecords = [];
        this.selectAll = false;
      }
    },
    // 新增记录功能
    addRecord() {
      this.overtimeRecords.push(this.getEmptyRecord());
      this.updateSelectAll();
    },
    // 保存数据功能
    async saveData() {
      try {
        if (this.overtimeRecords.length === 0) {
          this.$message.error('请至少添加一条记录');
          return;
        }

        // 验证必填字段
        for (const record of this.overtimeRecords) {
          if (!record.employeeId) throw new Error('请填写工号');
          if (!record.name) throw new Error('请填写姓名');
          if (!record.overtimeDate) throw new Error('请选择加班日期');
        }

        if (!this.applicationDate) throw new Error('请选择申请日期');

        const params = {
          applicationDate: this.applicationDate,
          overtimeRecords: this.overtimeRecords.map(record => ({
            ...record,
            id: record.id || null
          })),
          applicant: this.applicant,
          reviewer: this.reviewer,
          approver: this.approver
        };

        await saveOvertimeApply(params);
        this.$message.success('保存成功');
        this.$router.push('/main/renshi/kaoqing/jiabansq-list');
      } catch (error) {
        this.$message.error('保存失败：' + error.message);
      }
    },
    printForm() {
      window.print();
    }
  }
};
</script>
<style scoped lang="scss">
.overtime-apply-form {
  font-family: '宋体', sans-serif;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  max-width: 1200px;
  margin: 0 auto;
  height: calc(100vh - 40px);
}

.header-links {
  display: flex;
  margin-bottom: 20px;
  justify-content: space-between;
  position: relative;
}

.header-links router-link {
  color: #007bff;
  text-decoration: none;
}

.header-links router-link:hover {
  text-decoration: underline;
}

.company-name,
.form-title {
  text-align: center;
  color: #333;
}

.apply-date {
  margin-bottom: 20px;
}

.record-table-container {
  overflow-x: auto;
  max-width: 100%;
  max-height: 200px;
  overflow: auto;
}

table {
  border-collapse: collapse;
  width: 100%;
  text-align: center;
}

tr td {
  /* background-color: #f2f2f2; */
  padding: 3px;
  white-space: nowrap;
}

th {

  padding: 8px;
  white-space: nowrap;
}

.record-table {
  border-collapse: collapse;
  width: 100%;
  text-align: center;
}

.record-table th {
  background-color: #f2f2f2;
}

.button-group {
  margin-bottom: 20px;
}

.button-group button {
  padding: 8px 16px;
  margin-right: 10px;
  border: none;
  border-radius: 4px;
  background-color: #007bff;
  color: white;
  cursor: pointer;
}

.button-group button:hover {
  background-color: #0056b3;
}

.info-group {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.info-group input {
  padding: 8px;
}

input {
  text-align: center;
  width: 100%;
  border: none;
}

.approval-info {
  padding: 10px 0px;
  // background-color: #fff;
  border-radius: 4px;

  .approval-row {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .approval-item {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 20px;

      &:first-child {
        padding-left: 0;
      }

      &:last-child {
        padding-right: 0;
      }

      .label {
        white-space: nowrap;
        margin-right: 10px;
        color: #606266;
      }

      .input {
        width: 200px;
      }
    }
  }
}

@media print {
  .overtime-apply-form {
    box-shadow: none;
  }

  .but,
  .checkbox {
    display: none !important;
  }

  .form {
    margin: 0px !important;
    width: 280mm !important;
  }

  ::v-deep input.el-input__inner {
    border: none;
  }
}
</style>